import os
import requests
import socket
from configparser import ConfigParser
import win32con
import win32api
import OperateReg
import shutil
import AutoWifiGui

class AutoWifi:
    types = ['cmcc', 'telecom', 'unicom', 'founder', 'free']
    inputTypes = ['移动', '电信', '联通', '单宽', '内网']
    # 检查输入
    def __init__(self):
        self.IP = str(socket.gethostbyname(socket.gethostname()))
        self.url = "http://1.1.1.1:801/eportal/?c=ACSetting&a=Login&protocol=http:&hostname=1.1.1.1&iTermType=1&wlanuserip="+self.IP+"&wlanacip=10.10.9.200&mac=00-00-00-00-00-00&ip="+self.IP+"&enAdvert=0&queryACIP=0&loginMethod=1"
        key = win32api.RegOpenKey(win32con.HKEY_CURRENT_USER,
                                  r'Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders', 0,
                                  win32con.KEY_ALL_ACCESS)
        self.save_path = os.path.join(win32api.RegQueryValueEx(key,'Personal')[0],'AutoWifi','info.ini')
        self.uninstall_lock = os.path.join(win32api.RegQueryValueEx(key,'Personal')[0],'AutoWifi','uninstall.lock')
        if os.path.exists(self.save_path) and not os.path.exists(self.uninstall_lock):
            self.deleteAllFile()
        if __name__ == "__main__":
            self.IsFirst()
            self.Connect()

    def checkInputing(self,username,password,ISP):
        self.DDDDD = username
        self.upass = password
        self.ISP = ISP
        a = self.inputTypes.index(self.ISP)
        self.ISP = self.types[a]
        self.DDDDD = int(self.DDDDD)
        self.upass = int(self.upass)

    # 判断是否存在
    def IsFirst(self):
        # 已经存在
        if os.path.exists(self.save_path):
            conf = ConfigParser()
            conf.read(self.save_path)
            self.DDDDD = conf['Info']['Username']
            self.upass = conf['Info']['Password']
            self.ISP = conf['Info']['ISP']
        else:
            win = AutoWifiGui.Win()
            win.mainloop()
            # self.intoFile()

    # 连接网络
    def deleteAllFile(self):
        OperateReg.cancelAutoStartup()
        os.remove(self.save_path)
        try:
            shutil.rmtree("./")
        except PermissionError:
            pass
    def Connect(self):
        post_dict = {
            'DDDDD': ',0,' + str(self.DDDDD) + '@' + self.ISP,
            'upass': str(self.upass),
            'R1': '0',
            'R2': '0',
            'R3': '0',
            'R6': '0',
            'para': '00',
            '0MKKey': '123456',
            'buttonClicked': '',
            'redirect_url': '',
            'err_flag': '',
            'username': '',
            'password': '',
            'user': '',
            'cmd': '',
            'Login': ''
        }
        header = {
            "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7",
            "Accept-Encoding": "gzip, deflate",
            "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6",
            "Cache-Control": "max-age=0",
            "Host": "1.1.1.1:801",
            "Origin": "http://1.1.1.1",
            "Referer": "http: // 1.1.1.1/",
            "Content-Length": "164",
            "Upgrade-Insecure-Requests": "1",
            "Connection": "keep-alive",
            "Content-Type": "application/x-www-form-urlencoded",
            "Cookie": "program=NEW; ip="+self.IP+"; vlan=0; ssid=null; areaID=null; ISP_select=@"+self.ISP+"; md5_login2=%2C0%2C"+str(self.DDDDD)+"@"+str(self.ISP)+"%7C"+str(self.upass),
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Safari/537.36 Edg/116.0.1938.76"
        }
        res = requests.post(self.url, data=post_dict,headers=header)
        res.encoding = res.apparent_encoding
        dataBack = res
        # if (dataBack.status_code == "200"):
        #     print("连接成功")
        # else:
        #     print("连接失败")

    def intoFile(self):
        self.checkInputing(AutoWifiGui.username, AutoWifiGui.password, AutoWifiGui.ISP)
        try:
            os.makedirs(os.path.dirname(self.save_path))
        except FileExistsError:
            pass
        info = open(self.save_path, "w")
        info.close()
        conf = ConfigParser()
        conf.add_section("Info")
        conf.set("Info", 'Username', str(self.DDDDD))
        conf.set("Info", 'Password', str(self.upass))
        conf.set("Info", 'ISP', self.ISP)
        try:
            with open(self.save_path, mode="w", encoding='utf-8') as info:
                conf.write(info)
            with open(self.uninstall_lock, "w", encoding="utf-8") as lock:
                lock.write("此文件删除后再重启即可干净有效地卸载AutoWifi(自动连接校园网)程序")
                OperateReg.setAutoStartup()
            win32api.MessageBox(0, '恭喜成功安装,关闭窗口即可', 'AutoWifi提示',
                                win32con.MB_OK | win32con.MB_ICONEXCLAMATION)
        except Exception as e:
            win32api.MessageBox(0, '安装失败:' + str(e), 'AutoWifi提示', win32con.MB_OK | win32con.MB_ICONEXCLAMATION)


if __name__ == "__main__":
    AutoWifi()
